<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="服务器信息" name="server">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>服务器基本信息</span>
              <el-button type="primary" size="small" @click="refreshServerInfo">
                <el-icon><Refresh /></el-icon> 刷新
              </el-button>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="操作系统">{{ serverInfo.os }}</el-descriptions-item>
            <el-descriptions-item label="服务器时间">{{ serverInfo.time }}</el-descriptions-item>
            <el-descriptions-item label="PHP版本">{{ serverInfo.php_version }}</el-descriptions-item>
            <el-descriptions-item label="时区">{{ serverInfo.timezone }}</el-descriptions-item>
            <el-descriptions-item label="服务器软件">{{ serverInfo.server_software }}</el-descriptions-item>
            <el-descriptions-item label="数据库版本">{{ serverInfo.db_type }} {{ serverInfo.db_version }}</el-descriptions-item>
          </el-descriptions>

          <el-divider content-position="left">资源使用情况</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <h4>CPU使用率</h4>
              <el-progress :percentage="serverInfo.cpu_usage || 0" :format="percentFormat" />
              <div v-if="serverInfo.cpu_model" class="mt-2 text-muted">型号: {{ serverInfo.cpu_model }}</div>
              <div v-if="serverInfo.cpu_cores" class="text-muted">核心数: {{ serverInfo.cpu_cores }}</div>
            </el-col>
            <el-col :span="12">
              <h4>内存使用率</h4>
              <el-progress :percentage="serverInfo.memory_usage || 0" :format="percentFormat" />
              <div v-if="serverInfo.memory_total" class="mt-2 text-muted">总内存: {{ serverInfo.memory_total }}</div>
              <div v-if="serverInfo.memory_used" class="text-muted">已用: {{ serverInfo.memory_used }}</div>
              <div v-if="serverInfo.memory_free" class="text-muted">剩余: {{ serverInfo.memory_free }}</div>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="mt-4">
            <el-col :span="24">
              <h4>磁盘使用率</h4>
              <el-progress :percentage="serverInfo.disk_usage || 0" :format="percentFormat" />
              <div class="mt-2 text-muted">总空间: {{ serverInfo.disk_total }}</div>
              <div class="text-muted">已用: {{ serverInfo.disk_used }}</div>
              <div class="text-muted">剩余: {{ serverInfo.disk_free }}</div>
            </el-col>
          </el-row>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="系统状态" name="status">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="status-card">
              <div class="status-card-header">
                <div class="status-title">用户总数</div>
                <el-icon class="status-icon user-icon"><User /></el-icon>
              </div>
              <div class="status-value">{{ systemStats.user?.total || 0 }}</div>
              <div class="status-footer">
                <div>今日新增: {{ systemStats.user?.today || 0 }}</div>
                <div>活跃用户: {{ systemStats.user?.active || 0 }}</div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :span="6">
            <el-card class="status-card">
              <div class="status-card-header">
                <div class="status-title">设备总数</div>
                <el-icon class="status-icon device-icon"><Monitor /></el-icon>
              </div>
              <div class="status-value">{{ systemStats.device?.total || 0 }}</div>
              <div class="status-footer">
                <div>在线设备: {{ systemStats.device?.online || 0 }}</div>
                <div>在线率: {{ systemStats.device?.online_rate || 0 }}%</div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="status-card">
              <div class="status-card-header">
                <div class="status-title">数据总量</div>
                <el-icon class="status-icon data-icon"><DataAnalysis /></el-icon>
              </div>
              <div class="status-value">{{ systemStats.data?.total || 0 }}</div>
              <div class="status-footer">
                <div>今日数据: {{ systemStats.data?.today || 0 }}</div>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="status-card">
              <div class="status-card-header">
                <div class="status-title">操作日志</div>
                <el-icon class="status-icon log-icon"><Document /></el-icon>
              </div>
              <div class="status-value">{{ systemStats.log?.total || 0 }}</div>
              <div class="status-footer">
                <div>今日操作: {{ systemStats.log?.today || 0 }}</div>
                <div>成功率: {{ systemStats.log?.success_rate || 0 }}%</div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="mt-4">
          <el-col :span="24">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>在线用户 ({{ onlineUsers.total || 0 }})</span>
                  <el-button type="primary" size="small" @click="refreshOnlineUsers">
                    <el-icon><Refresh /></el-icon> 刷新
                  </el-button>
                </div>
              </template>
              
              <el-form :inline="true" class="search-form">
                <el-form-item label="用户名">
                  <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable @keyup.enter="searchOnlineUsers" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="searchOnlineUsers">
                    <el-icon><Search /></el-icon> 搜索
                  </el-button>
                  <el-button @click="resetQuery">
                    <el-icon><Refresh /></el-icon> 重置
                  </el-button>
                </el-form-item>
              </el-form>
              
              <el-table :data="onlineUsers.data || []" border>
                <el-table-column prop="username" label="用户名" />
                <el-table-column prop="name" label="姓名" />
                <el-table-column prop="department" label="部门" />
                <el-table-column prop="ip" label="登录IP" />
                <el-table-column prop="last_login_time" label="登录时间" />
              </el-table>
              
              <el-pagination
                v-if="onlineUsers.total > 0"
                class="mt-4 text-right"
                :current-page="queryParams.page"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="queryParams.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="onlineUsers.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="缓存监控" name="cache">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>缓存信息</span>
              <el-button type="primary" size="small" @click="refreshCacheInfo">
                <el-icon><Refresh /></el-icon> 刷新
              </el-button>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="total-info mb-4">
                <span class="label">总缓存大小: </span>
                <span class="value">{{ cacheInfo.total }}</span>
                <el-button type="danger" size="small" class="ml-4" @click="handleClearCache('all')">
                  <el-icon><Delete /></el-icon> 清空所有缓存
                </el-button>
              </div>
            </el-col>
          </el-row>

          <el-table :data="cacheInfoList" border>
            <el-table-column prop="name" label="缓存名称" />
            <el-table-column prop="path" label="缓存路径" />
            <el-table-column prop="size" label="缓存大小" />
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button type="danger" size="small" @click="handleClearCache(row.type)">
                  <el-icon><Delete /></el-icon> 清空
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="数据库监控" name="database">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>数据库信息</span>
              <el-button type="primary" size="small" @click="refreshDatabaseInfo">
                <el-icon><Refresh /></el-icon> 刷新
              </el-button>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="total-info mb-4">
                <span class="label">数据库名: </span>
                <span class="value">{{ databaseInfo.database }}</span>
                <span class="ml-4 label">表数量: </span>
                <span class="value">{{ databaseInfo.table_count }}</span>
                <span class="ml-4 label">总大小: </span>
                <span class="value">{{ databaseInfo.total_size }}</span>
              </div>
            </el-col>
          </el-row>

          <el-table :data="databaseInfo.tables || []" border>
            <el-table-column prop="name" label="表名" />
            <el-table-column prop="engine" label="引擎" />
            <el-table-column prop="rows" label="行数" />
            <el-table-column prop="data_size" label="数据大小" />
            <el-table-column prop="index_size" label="索引大小" />
            <el-table-column prop="total_size" label="总大小" />
            <el-table-column prop="create_time" label="创建时间" />
            <el-table-column prop="update_time" label="更新时间" />
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getServerInfo,
  getSystemStatistics,
  getOnlineUsers,
  getDatabaseInfo,
  getCacheInfo,
  clearCache
} from '@/api/system'
import { User, Monitor, DataAnalysis, Document, Refresh, Search, Delete } from '@element-plus/icons-vue'

// 激活的标签页
const activeTab = ref('server')

// 服务器信息
const serverInfo = ref({})
const systemStats = ref({})
const onlineUsers = ref({})
const databaseInfo = ref({})
const cacheInfo = ref({})

// 查询参数
const queryParams = reactive({
  username: '',
  page: 1,
  pageSize: 10
})

// 缓存信息列表
const cacheInfoList = ref([])

// 格式化百分比
const percentFormat = (percentage) => {
  return percentage + '%'
}

// 初始化页面
onMounted(() => {
  refreshServerInfo()
  refreshSystemStats()
  refreshOnlineUsers()
  refreshDatabaseInfo()
  refreshCacheInfo()
})

// 刷新服务器信息
const refreshServerInfo = async () => {
  try {
    const res = await getServerInfo()
    serverInfo.value = res.data
  } catch (error) {
    console.error(error)
    ElMessage.error('获取服务器信息失败')
  }
}

// 刷新系统统计信息
const refreshSystemStats = async () => {
  try {
    const res = await getSystemStatistics()
    systemStats.value = res.data
  } catch (error) {
    console.error(error)
    ElMessage.error('获取系统统计信息失败')
  }
}

// 刷新在线用户列表
const refreshOnlineUsers = async () => {
  try {
    const res = await getOnlineUsers(queryParams)
    onlineUsers.value = res.data
  } catch (error) {
    console.error(error)
    ElMessage.error('获取在线用户列表失败')
  }
}

// 刷新数据库信息
const refreshDatabaseInfo = async () => {
  try {
    const res = await getDatabaseInfo()
    databaseInfo.value = res.data
  } catch (error) {
    console.error(error)
    ElMessage.error('获取数据库信息失败')
  }
}

// 刷新缓存信息
const refreshCacheInfo = async () => {
  try {
    const res = await getCacheInfo()
    cacheInfo.value = res.data
    
    // 格式化缓存信息列表
    cacheInfoList.value = [
      { name: '数据缓存', path: res.data.cache.path, size: res.data.cache.size, type: 'cache' },
      { name: '日志文件', path: res.data.log.path, size: res.data.log.size, type: 'log' },
      { name: '临时文件', path: res.data.temp.path, size: res.data.temp.size, type: 'temp' },
      { name: '上传文件', path: res.data.upload.path, size: res.data.upload.size, type: 'upload' }
    ]
  } catch (error) {
    console.error(error)
    ElMessage.error('获取缓存信息失败')
  }
}

// 搜索在线用户
const searchOnlineUsers = () => {
  queryParams.page = 1
  refreshOnlineUsers()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.username = ''
  queryParams.page = 1
  refreshOnlineUsers()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  refreshOnlineUsers()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  refreshOnlineUsers()
}

// 清空缓存
const handleClearCache = (type) => {
  ElMessageBox.confirm(`确定要清空${type === 'all' ? '所有' : '该'}缓存吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await clearCache(type)
      ElMessage.success(res.msg || '清空缓存成功')
      refreshCacheInfo()
    } catch (error) {
      console.error(error)
      ElMessage.error('清空缓存失败')
    }
  }).catch(() => {})
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mt-2 {
  margin-top: 5px;
}

.mt-4 {
  margin-top: 15px;
}

.mb-4 {
  margin-bottom: 15px;
}

.ml-4 {
  margin-left: 15px;
}

.text-right {
  text-align: right;
}

.text-muted {
  color: #909399;
  font-size: 14px;
}

/* 状态卡片样式 */
.status-card {
  height: 160px;
  position: relative;
  overflow: hidden;
}

.status-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.status-title {
  font-size: 16px;
  font-weight: bold;
}

.status-icon {
  font-size: 24px;
}

.user-icon {
  color: #409EFF;
}

.device-icon {
  color: #67C23A;
}

.data-icon {
  color: #E6A23C;
}

.log-icon {
  color: #F56C6C;
}

.status-value {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 15px;
}

.status-footer {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 14px;
}

/* 总信息样式 */
.total-info {
  background-color: #f8f8f9;
  padding: 15px;
  border-radius: 4px;
}

.total-info .label {
  font-weight: bold;
}

.total-info .value {
  color: #409EFF;
}

.search-form {
  margin-bottom: 15px;
}
</style> 